<template>
  <a-modal
    v-model="modalVisible"
    title="登录"
    @cancel="handleModalCancel"
  >
    <a-form layout="horizontal" :form="form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-form-item label="账号">
        <a-input
          v-decorator="[
            'email',
            {
              rules: [{ required: true, message: '邮箱不能为空' }],
              validateFirst: true,
              initialValue: 'test001@qq.com',
            }
          ]"
          placeholder="请输入邮箱"></a-input>
      </a-form-item>
      
      <a-form-item label="密码">
        <a-input
          v-decorator="[
            'password',
            {
              rules: [{ required: true, message: '密码不能为空' }],
              validateFirst: true,
              initialValue: 'q12345',
            }
          ]"
          type="password"
          placeholder="请输入密码"></a-input>
      </a-form-item>
    </a-form>

    <template slot="footer">
      <a-button class="ui-mr-8" type="default" @click="handleModalCancel">取消</a-button>
      <a-button class="submit-btn" type="primary" @click="submitLoginForm">登录</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" >
import { Component, Vue, Prop, Model, Watch, Emit } from 'vue-property-decorator';
import { WrappedFormUtils } from 'ant-design-vue/types/form/form';

@Component
export default class LoginModalForm extends Vue {
  @Watch('visible')
  onWatchVisible(newVal: boolean, oldVal: boolean): void {
    this.modalVisible = newVal;
  }

  @Model('change', { type: Boolean, required: false, default: false })
  readonly visible?: boolean;

  @Emit('change')
  onChange(val: boolean): void {}

  modalVisible: boolean = false;
  form!: WrappedFormUtils;
  labelCol = { span: 4 };
  wrapperCol = { span: 20 };

  private beforeCreate(): void {
    this.form = this.$form.createForm(this, { name: 'normal_login' });
  }

  private created(): void {
    this.modalVisible = this.visible || false; 
  }

  handleModalCancel(): void {
    this.modalVisible = false;
    this.form.resetFields();
    this.onChange(false);
  }

  /**
   * 登录
   */
  submitLoginForm(): void {
    this.form.validateFields((err, values) => {
      if (err) return;
      this.$store.dispatch('user/login', { email: values.email, password: values.password }).then(res => {
        this.$message.success('登录成功');
        this.onChange(false);
      });
    });
  }
}
</script>

<style lang="scss" scoped>
</style>
